﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Telerik.WinControls;
using System.IO;
using System.Collections;
using Telerik.WinControls.UI;
using Telerik.WinControls.Data;
using log4net;
using QuanLyNhaSach.Report;

namespace QuanLyNhaSach
{
    public partial class frmBC_CongNoKhachHang : Form
    {
        //Tao Parttern Seleton
        static frmBC_CongNoKhachHang doituong = null;
        public static frmBC_CongNoKhachHang TaoDoiTuong()
        {
            if (doituong == null)
                doituong = new frmBC_CongNoKhachHang();
            return doituong;
        }        

        public frmBC_CongNoKhachHang()
        {
            InitializeComponent();
        }

        #region "Khai Báo Biến"        
        sv_QuanLyNhaSach.AdapterClient sv_QLNS = new sv_QuanLyNhaSach.AdapterClient();
        private ILog logger;
        DataSet ds_BCCongNo;
        ArrayList test_ListKH;
        ArrayList test_ListNCC;

        //Biến truyền qua Report
        DateTime TuNgay;
        DateTime DenNgay;
        string MaNCC;
        string MaKH;
        bool TrangThaiKH = true;
        #endregion

        #region "Ham chuyen so thanh chu"
        private static string Chu(string gNumber)
        {            
            string result = "";
            switch (gNumber.ToString())
            {
                case "0":
                    result = "không";
                    break;
                case "1":
                    result = "một";
                    break;
                case "2":
                    result = "hai";
                    break;
                case "3":
                    result = "ba";
                    break;
                case "4":
                    result = "bốn";
                    break;
                case "5":
                    result = "năm";
                    break;
                case "6":
                    result = "sáu";
                    break;
                case "7":
                    result = "bảy";
                    break;
                case "8":
                    result = "tám";
                    break;
                case "9":
                    result = "chín";
                    break;
            }
            return result;
        }
        private static string Donvi(string so)
        {
            string Kdonvi = "";

            if (so.Equals("1"))
                Kdonvi = "";
            if (so.Equals("2"))
                Kdonvi = "nghìn";
            if (so.Equals("3"))
                Kdonvi = "triệu";
            if (so.Equals("4"))
                Kdonvi = "tỷ";
            if (so.Equals("5"))
                Kdonvi = "nghìn tỷ";
            if (so.Equals("6"))
                Kdonvi = "triệu tỷ";
            if (so.Equals("7"))
                Kdonvi = "tỷ tỷ";

            return Kdonvi;
        }
        private static string Tach(string tach3)
        {
            string Ktach = "";
            if (tach3.Equals("000"))
                return "";
            if (tach3.Length == 3)
            {
                string tr = tach3.Trim().Substring(0, 1).ToString().Trim();
                string ch = tach3.Trim().Substring(1, 1).ToString().Trim();
                string dv = tach3.Trim().Substring(2, 1).ToString().Trim();
                if (tr.Equals("0") && ch.Equals("0"))
                    Ktach = " không trăm lẻ " + Chu(dv.ToString().Trim()) + " ";
                if (!tr.Equals("0") && ch.Equals("0") && dv.Equals("0"))
                    Ktach = Chu(tr.ToString().Trim()).Trim() + " trăm ";
                if (!tr.Equals("0") && ch.Equals("0") && !dv.Equals("0"))
                    Ktach = Chu(tr.ToString().Trim()).Trim() + " trăm lẻ " + Chu(dv.Trim()).Trim() + " ";
                if (tr.Equals("0") && Convert.ToInt32(ch) > 1 && Convert.ToInt32(dv) > 0 && !dv.Equals("5"))
                    Ktach = " không trăm " + Chu(ch.Trim()).Trim() + " mươi " + Chu(dv.Trim()).Trim() + " ";
                if (tr.Equals("0") && Convert.ToInt32(ch) > 1 && dv.Equals("0"))
                    Ktach = " không trăm " + Chu(ch.Trim()).Trim() + " mươi ";
                if (tr.Equals("0") && Convert.ToInt32(ch) > 1 && dv.Equals("5"))
                    Ktach = " không trăm " + Chu(ch.Trim()).Trim() + " mươi lăm ";
                if (tr.Equals("0") && ch.Equals("1") && Convert.ToInt32(dv) > 0 && !dv.Equals("5"))
                    Ktach = " không trăm mười " + Chu(dv.Trim()).Trim() + " ";
                if (tr.Equals("0") && ch.Equals("1") && dv.Equals("0"))
                    Ktach = " không trăm mười ";
                if (tr.Equals("0") && ch.Equals("1") && dv.Equals("5"))
                    Ktach = " không trăm mười lăm ";
                if (Convert.ToInt32(tr) > 0 && Convert.ToInt32(ch) > 1 && Convert.ToInt32(dv) > 0 && !dv.Equals("5"))
                    Ktach = Chu(tr.Trim()).Trim() + " trăm " + Chu(ch.Trim()).Trim() + " mươi " + Chu(dv.Trim()).Trim() + " ";
                if (Convert.ToInt32(tr) > 0 && Convert.ToInt32(ch) > 1 && dv.Equals("0"))
                    Ktach = Chu(tr.Trim()).Trim() + " trăm " + Chu(ch.Trim()).Trim() + " mươi ";
                if (Convert.ToInt32(tr) > 0 && Convert.ToInt32(ch) > 1 && dv.Equals("5"))
                    Ktach = Chu(tr.Trim()).Trim() + " trăm " + Chu(ch.Trim()).Trim() + " mươi lăm ";
                if (Convert.ToInt32(tr) > 0 && ch.Equals("1") && Convert.ToInt32(dv) > 0 && !dv.Equals("5"))
                    Ktach = Chu(tr.Trim()).Trim() + " trăm mười " + Chu(dv.Trim()).Trim() + " ";

                if (Convert.ToInt32(tr) > 0 && ch.Equals("1") && dv.Equals("0"))
                    Ktach = Chu(tr.Trim()).Trim() + " trăm mười ";
                if (Convert.ToInt32(tr) > 0 && ch.Equals("1") && dv.Equals("5"))
                    Ktach = Chu(tr.Trim()).Trim() + " trăm mười lăm ";

            }


            return Ktach;

        }
        public static string So_chu(double gNum)
        {
            if (gNum == 0)
                return "Không đồng";

            string lso_chu = "";
            string tach_mod = "";
            string tach_conlai = "";
            double Num = Math.Round(gNum, 0);
            string gN = Convert.ToString(Num);
            int m = Convert.ToInt32(gN.Length / 3);
            int mod = gN.Length - m * 3;
            string dau = "[+]";

            // Dau [+ , - ]
            if (gNum < 0)
                dau = "[-]";
            dau = "";

            // Tach hang lon nhat
            if (mod.Equals(1))
                tach_mod = "00" + Convert.ToString(Num.ToString().Trim().Substring(0, 1)).Trim();
            if (mod.Equals(2))
                tach_mod = "0" + Convert.ToString(Num.ToString().Trim().Substring(0, 2)).Trim();
            if (mod.Equals(0))
                tach_mod = "000";
            // Tach hang con lai sau mod :
            if (Num.ToString().Length > 2)
                tach_conlai = Convert.ToString(Num.ToString().Trim().Substring(mod, Num.ToString().Length - mod)).Trim();

            ///don vi hang mod 
            int im = m + 1;
            if (mod > 0)
                lso_chu = Tach(tach_mod).ToString().Trim() + " " + Donvi(im.ToString().Trim());
            /// Tach 3 trong tach_conlai

            int i = m;
            int _m = m;
            int j = 1;
            string tach3 = "";
            string tach3_ = "";

            while (i > 0)
            {
                tach3 = tach_conlai.Trim().Substring(0, 3).Trim();
                tach3_ = tach3;
                lso_chu = lso_chu.Trim() + " " + Tach(tach3.Trim()).Trim();
                m = _m + 1 - j;
                if (!tach3_.Equals("000"))
                    lso_chu = lso_chu.Trim() + " " + Donvi(m.ToString().Trim()).Trim();
                tach_conlai = tach_conlai.Trim().Substring(3, tach_conlai.Trim().Length - 3);

                i = i - 1;
                j = j + 1;
            }
            if (lso_chu.Trim().Substring(0, 1).Equals("k"))
                lso_chu = lso_chu.Trim().Substring(10, lso_chu.Trim().Length - 10).Trim();
            if (lso_chu.Trim().Substring(0, 1).Equals("l"))
                lso_chu = lso_chu.Trim().Substring(2, lso_chu.Trim().Length - 2).Trim();
            if (lso_chu.Trim().Length > 0)
                lso_chu = dau.Trim() + " " + lso_chu.Trim().Substring(0, 1).Trim().ToUpper() + lso_chu.Trim().Substring(1, lso_chu.Trim().Length - 1).Trim() + " đồng chẵn.";

            return lso_chu.ToString().Trim();

        }
        #endregion

        private void frmBC_CongNoKhachHang_Load(object sender, EventArgs e)
        {
            dtpTuNgay.Value = DateTime.Now;
            dtpDenNgay.Value = DateTime.Now;
            logger = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
            //Load Danh Sach Nha Cung Cap
            Load_DanhSach_NhaCungCap();
            //Load Danh Sach Khach Hang
            Load_DanhSach_KhachHang();
            //Kiem tra tinh cong no
            if (rdbtn_KhachHang.Checked == true)
                mcbb_KhachHang.Enabled = true;            
        }

        private void Load_DanhSach_NhaCungCap()
        {
            try
            {
                //Chinh do dai cua cac cot trong muiltcombobox
                RadMultiColumnComboBoxElement multiColumnComboElement = this.mcbb_NhaCungCap.MultiColumnComboBoxElement;
                multiColumnComboElement.DropDownSizingMode = SizingMode.UpDownAndRightBottom;
                multiColumnComboElement.DropDownMinSize = new Size(500, 200);

                DataSet ds_NhaCungCap = new DataSet();
                ds_NhaCungCap.ReadXml(new StringReader(sv_QLNS.LayDS_NhaCungCap()));
                if (ds_NhaCungCap.Tables.Count > 0)
                {
                    mcbb_NhaCungCap.DataSource = ds_NhaCungCap.Tables[0];
                    mcbb_NhaCungCap.DisplayMember = "TenNCC";
                    mcbb_NhaCungCap.ValueMember = "MaNCC";
                    mcbb_NhaCungCap.SelectedIndex = -1;      
                    //Them vao Danh sach NCC trong Test_ListNCC
                    test_ListNCC = new ArrayList();
                    for (int i = 0; i < ds_NhaCungCap.Tables[0].Rows.Count; i++)
                    {
                        test_ListNCC.Add(ds_NhaCungCap.Tables[0].Rows[i]["TenNCC"].ToString().Trim());
                    }
                }
                FilterDescriptor des_mh = new FilterDescriptor(this.mcbb_NhaCungCap.DisplayMember, FilterOperator.StartsWith, string.Empty);
                mcbb_NhaCungCap.EditorControl.FilterDescriptors.Add(des_mh);
            }
            catch (Exception ex)
            {
                logger.Error("Error: " + ex.Message);
            }
        }

        private void Load_DanhSach_KhachHang()
        {
            try
            {
                //Chinh do dai cua cac cot trong muiltcombobox
                RadMultiColumnComboBoxElement multiColumnComboElement = this.mcbb_KhachHang.MultiColumnComboBoxElement;
                multiColumnComboElement.DropDownSizingMode = SizingMode.UpDownAndRightBottom;
                multiColumnComboElement.DropDownMinSize = new Size(500, 200);

                DataSet ds_KhachHang = new DataSet();
                ds_KhachHang.ReadXml(new StringReader(sv_QLNS.LayDS_KhachHang()));
                if (ds_KhachHang.Tables.Count > 0)
                {
                    mcbb_KhachHang.DataSource = ds_KhachHang.Tables[0];
                    mcbb_KhachHang.DisplayMember = "HoTenKH";
                    mcbb_KhachHang.ValueMember = "MaKH";
                    mcbb_KhachHang.SelectedIndex = -1;
                    //Them vao Danh sach Khach Hang trong Test_ListKH
                    test_ListKH = new ArrayList();
                    for (int i = 0; i < ds_KhachHang.Tables[0].Rows.Count; i++)
                    {
                        test_ListKH.Add(ds_KhachHang.Tables[0].Rows[i]["HoTenKH"].ToString().Trim());
                    }
                }
                FilterDescriptor des_mh = new FilterDescriptor(this.mcbb_KhachHang.DisplayMember, FilterOperator.StartsWith, string.Empty);
                mcbb_KhachHang.EditorControl.FilterDescriptors.Add(des_mh);
            }
            catch (Exception ex)
            {
                logger.Error("Error: " + ex.Message);
            }
        }
        
        private void rdbtn_KhachHang_CheckedChanged(object sender, EventArgs e)
        {
            if (rdbtn_KhachHang.Checked == true)
            {
                mcbb_KhachHang.Enabled = true;
                mcbb_NhaCungCap.Enabled = false;
                mcbb_NhaCungCap.SelectedIndex = -1;
                TrangThaiKH = true;
            }
            else
            {
                mcbb_KhachHang.Enabled = false;
                mcbb_NhaCungCap.Enabled = true;
                mcbb_KhachHang.SelectedIndex = -1;
                TrangThaiKH = false;
            }
        }        

        private void btn_Loc_Click(object sender, EventArgs e)
        {
            try
            {
                if (dtpTuNgay.Value > dtpDenNgay.Value)
                {
                    MessageBox.Show("Vui lòng chọn Từ Ngày phải nhỏ hơn hoặc bằng Đến Ngày.","Thông Báo", MessageBoxButtons.OK);
                    return;
                }                
                //Khai bao bien truyen vao Store
                TuNgay = dtpTuNgay.Value;
                DenNgay = dtpDenNgay.Value;
                if (mcbb_NhaCungCap.Text.Trim() != "")
                {
                    if (!test_ListNCC.Contains(mcbb_NhaCungCap.Text.Trim()))
                    {
                        MessageBox.Show("Vui lòng nhập đúng thông tin nhà cung cấp cần lọc.", "Cảnh Báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }
                    MaNCC = mcbb_NhaCungCap.SelectedValue.ToString();                    
                }
                else
                    MaNCC = "";

                if (mcbb_KhachHang.Text.Trim() != "")
                {
                    if (!test_ListKH.Contains(mcbb_KhachHang.Text.Trim()))
                    {
                        MessageBox.Show("Vui lòng nhập đúng thông tin khách hàng cần lọc.", "Cảnh Báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }
                    MaKH = mcbb_KhachHang.SelectedValue.ToString();                    
                }
                else
                    MaKH = "";

                ds_BCCongNo = new DataSet();
                ds_BCCongNo.ReadXml(new StringReader(sv_QLNS.BaoCaoCongNo(TuNgay, DenNgay, MaNCC, MaKH,TrangThaiKH)));                
                if (ds_BCCongNo.Tables.Count > 0)
                {
                    for (int i = 0; i < ds_BCCongNo.Tables[0].Rows.Count; i++)
                    {
                        ds_BCCongNo.Tables[0].Rows[i]["NoDauKy"] = double.Parse(ds_BCCongNo.Tables[0].Rows[i]["NoDauKy"].ToString()).ToString("#,##0");
                        ds_BCCongNo.Tables[0].Rows[i]["TienMuaHang"] = double.Parse(ds_BCCongNo.Tables[0].Rows[i]["TienMuaHang"].ToString()).ToString("#,##0");
                        ds_BCCongNo.Tables[0].Rows[i]["TienTraLai"] = double.Parse(ds_BCCongNo.Tables[0].Rows[i]["TienTraLai"].ToString()).ToString("#,##0");
                        ds_BCCongNo.Tables[0].Rows[i]["ThanhToan"] = double.Parse(ds_BCCongNo.Tables[0].Rows[i]["ThanhToan"].ToString()).ToString("#,##0");
                        ds_BCCongNo.Tables[0].Rows[i]["TienThuChi"] = double.Parse(ds_BCCongNo.Tables[0].Rows[i]["TienThuChi"].ToString()).ToString("#,##0");
                        ds_BCCongNo.Tables[0].Rows[i]["NoCuoiKy"] = double.Parse(ds_BCCongNo.Tables[0].Rows[i]["NoCuoiKy"].ToString()).ToString("#,##0");
                    }
                    gv_congno2.DataSource = ds_BCCongNo.Tables[0];
                    if (gv_congno2.Rows.Count > 0)
                    {
                        for (int i = 0; i < gv_congno2.Rows.Count; i++)
                        {
                            gv_congno2.Rows[i].Cells["STT"].Value = i + 1;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error("Error: " + ex.Message);
                MessageBox.Show("Không tìm thấy thông tin Công Nợ này. Vui lòng nhập lại khác!!!","Thông Báo", MessageBoxButtons.OK);
            }
        }

        private void btn_XemIn_Click(object sender, EventArgs e)
        {
            try
            {
                string chuyentienthanhchu;
                double TongTienTam = 0;
                if (gv_congno2.Rows.Count > 0)
                {
                    for (int i = 0; i < gv_congno2.Rows.Count; i++)
                    {
                        TongTienTam += double.Parse(gv_congno2.Rows[i].Cells["NoCuoiKy"].Value.ToString());
                    }
                }
                if (TongTienTam < 0)
                {                    
                    chuyentienthanhchu = "Nợ -- " + So_chu(Math.Abs(TongTienTam));
                }
                else
                    chuyentienthanhchu = So_chu(TongTienTam);
                frmRP_BC_CongNo fBC_CongNo = new frmRP_BC_CongNo();
                fBC_CongNo.TuNgay = TuNgay;
                fBC_CongNo.DenNgay = DenNgay;
                fBC_CongNo.MaNCC = MaNCC;
                fBC_CongNo.MaKH = MaKH;
                fBC_CongNo.TrangThaiKH = TrangThaiKH;
                fBC_CongNo.ChuyenTienThanhChu = chuyentienthanhchu;
                fBC_CongNo.ShowDialog();
            }
            catch (Exception ex) { logger.Error("Error: " + ex.Message); }
        }

        private void bt_xoa_Click(object sender, EventArgs e)
        {
            Application.OpenForms["FormChinh2"].Activate();
            Application.OpenForms["FormChinh2"].Show();
            this.Close();
        }
    }
}
